<template>
    <div class="timetable-container">
        <!-- 学生选择部分 -->
        <div class="class-select" v-if="!isStudent">
            <div class="select-info">
                <el-tag size="large" type="info">
                    所选学生：{{ getSelectedStudentName() }}
                </el-tag>
            </div>
            <div class="select-filter">
                <el-tag size="large" type="primary">
                    年级：
                </el-tag>
                <el-tree-select v-model="selectedGlobalDeptId" :data="enabledDeptOptions"
                    :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="选择年级"
                    check-strictly default-expand-all style="width: 150px;" />
                <el-tag size="large" type="primary">
                    班级：
                </el-tag>
                <el-select v-model="selectedGlobalClassId" placeholder="选择班级" clearable style="width: 150px;">
                    <el-option v-for="item in allClassData" :key="item.postId" :label="item.postName"
                        :value="item.postId" />
                </el-select>
                <el-tag size="large" type="primary">
                    学生：
                </el-tag>
                <el-select v-model="selectedGlobalStudentId" placeholder="选择学生" clearable style="width: 150px;">
                    <el-option v-for="item in allStudentData" :key="item.userId" :label="item.userName"
                        :value="item.userId" />
                </el-select>
            </div>
        </div>

        <!-- 无学生数据提示 -->
        <el-empty v-if="showEmptyStudentTip" description="当前班级没有学生数据，请重新选择年级班级！"></el-empty>

        <template v-if="!showEmptyStudentTip">
            <!-- 学生信息卡片 -->
            <el-card shadow="hover" class="info-card" v-if="selectedGlobalStudentId">
                <div class="student-info">
                    <el-button type="primary" size="small" @click="handleAddAttention"
                        v-hasPermi="['manage:attention_student:add']" class="focus-button">
                        设置为重点关注学生
                    </el-button>
                    <div class="student-avatar">
                        <img :src="getProcessedAvatar(studentInfo.avatar)" class="user-avatar" />
                    </div>
                    <div class="student-details">
                        <div class="info-row">
                            <div class="info-item">
                                <span class="label">学号：</span>
                                <span class="value">{{ studentInfo.userName || '--' }}</span>
                            </div>
                            <div class="info-item">
                                <span class="label">姓名：</span>
                                <span class="value">{{ studentInfo.nickName || '--' }}</span>
                            </div>
                        </div>
                        <div class="info-row">
                            <div class="info-item">
                                <span class="label">班级：</span>
                                <span class="value">{{ getSelectedClassName(studentInfo) }}</span>
                            </div>
                        </div>
                        <div class="info-row">
                            <div class="info-item">
                                <span class="label">总出勤率：</span>
                                <span class="value attendance-rate">{{ studentAttendanceRate }}%</span>
                            </div>
                        </div>
                    </div>
                </div>
            </el-card>

            <!-- 出勤统计卡片 -->
            <el-card shadow="hover" class="chart-card" v-if="selectedGlobalStudentId">
                <div class="card-header">
                    <div class="title">
                        <el-icon>
                            <TrendCharts />
                        </el-icon>
                        出勤统计
                    </div>
                    <div class="tabs">
                        <el-radio-group v-model="attendanceStatsPeriod" size="small">
                            <el-radio-button value="today">今日</el-radio-button>
                            <el-radio-button value="week">本周</el-radio-button>
                            <el-radio-button value="month">本月</el-radio-button>
                            <el-radio-button value="semester">本学期</el-radio-button>
                        </el-radio-group>
                    </div>
                </div>
                <!-- 调整后的出勤统计布局 -->
                <div class="attendance-stats-container">
                    <div class="attendance-stats-item">
                        <div class="stat-value">{{ attendanceStats.normal || 0 }}</div>
                        <div class="stat-label">本{{ periodText }}出勤次数</div>
                    </div>
                    <div class="attendance-stats-item">
                        <div class="stat-value">{{ attendanceStats.leave || 0 }}</div>
                        <div class="stat-label">本{{ periodText }}请假次数</div>
                    </div>
                    <div class="attendance-stats-item">
                        <div class="stat-value">{{ attendanceStats.late || 0 }}</div>
                        <div class="stat-label">本{{ periodText }}迟到次数</div>
                    </div>
                    <div class="attendance-stats-item">
                        <div class="stat-value">{{ attendanceStats.absent || 0 }}</div>
                        <div class="stat-label">本{{ periodText }}旷课次数</div>
                    </div>
                    <div class="attendance-stats-item">
                        <div class="stat-value attendance-rate">{{ attendanceStats.rate || 0 }}%</div>
                        <div class="stat-label">本{{ periodText }}出勤率</div>
                    </div>
                </div>
            </el-card>

            <!-- 各科目出勤统计卡片 -->
            <el-card shadow="hover" class="chart-card" v-if="selectedGlobalStudentId">
                <div class="card-header">
                    <div class="title">
                        <el-icon>
                            <Collection />
                        </el-icon>
                        各科目出勤次数统计
                    </div>
                    <div class="tabs">
                        <el-radio-group v-model="subjectStatsPeriod" size="small">
                            <el-radio-button value="today">今日</el-radio-button>
                            <el-radio-button value="week">本周</el-radio-button>
                            <el-radio-button value="month">本月</el-radio-button>
                            <el-radio-button value="semester">本学期</el-radio-button>
                        </el-radio-group>
                    </div>
                </div>
                <!-- 优化后的科目统计布局 -->
                <div class="subject-stats-grid">
                    <div class="subject-stats-item" v-for="item in subjectStats" :key="item.id">
                        <div class="stat-value">{{ item.count || 0 }}</div>
                        <div class="stat-label">{{ item.name }}</div>
                    </div>
                </div>
            </el-card>

            <!-- 各科目出勤率图表 -->
            <el-card shadow="hover" class="chart-card" v-if="selectedGlobalStudentId">
                <div class="card-header">
                    <div class="title">
                        <el-icon>
                            <TrendCharts />
                        </el-icon>
                        各科目出勤率统计
                    </div>
                    <div class="filter-container">
                        <el-radio-group v-model="subjectChartPeriod" size="small"
                            class="filter-item radio-group-inline">
                            <el-radio-button value="today">今日</el-radio-button>
                            <el-radio-button value="week">本周</el-radio-button>
                            <el-radio-button value="month">本月</el-radio-button>
                            <el-radio-button value="quarter">本季度</el-radio-button>
                            <el-radio-button value="semester">本学期</el-radio-button>
                        </el-radio-group>
                    </div>
                </div>
                <div ref="subjectBarChart" class="chart-container"></div>
            </el-card>

            <!-- 请假记录卡片 -->
            <el-card shadow="hover" class="chart-card" v-if="selectedGlobalStudentId">
                <div class="card-header">
                    <div class="title">
                        <el-icon>
                            <Calendar />
                        </el-icon>
                        今日考勤记录
                    </div>
                </div>
                <el-tabs v-model="leaveTabActive">
                    <el-tab-pane label="请假列表" name="leaveList">
                        <el-table :data="leaveRecords" style="width: 100%" border stripe>
                            <el-table-column prop="startTime" label="请假开始时间" width="180" />
                            <el-table-column prop="endTime" label="请假结束时间" width="180" />
                            <el-table-column prop="reason" label="请假原因">
                                <template #default="scope">
                                    <el-popover placement="top" width="200" trigger="hover">
                                        <p>{{ scope.row.reason }}</p>
                                        <template #reference>
                                            <span class="ellipsis">{{ scope.row.reason }}</span>
                                        </template>
                                    </el-popover>
                                </template>
                            </el-table-column>
                            <el-table-column prop="status" label="请假状态">
                                <template #default="scope">
                                    <el-tag :type="getLeaveStatusType(scope.row.status)">
                                        {{ getLeaveStatusText(scope.row.status) }}
                                    </el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="updateTime" label="更新时间" width="180" />
                            <el-table-column label="操作" width="100">
                                <template #default="scope">
                                    <el-button link type="primary" size="small" @click="viewLeaveDetail(scope.row)">
                                        查看详情
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                    <el-tab-pane label="迟到列表" name="lateList">
                        <el-table :data="lateRecords" style="width: 100%" border stripe>
                            <el-table-column prop="attendanceDate" label="日期" width="180" />
                            <el-table-column prop="course.courseName" label="课程" width="210" />
                            <el-table-column prop="subjectName" label="科目" width="120" />
                            <el-table-column prop="course.teacher.nickName" label="任课教师" width="120" />
                            <el-table-column prop="remark" label="迟到原因">
                                <template #default="scope">
                                    <span v-if="scope.row.remark">{{ scope.row.remark }}</span>
                                    <span v-else>无原因说明</span>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                    <el-tab-pane label="旷课列表" name="absentList">
                        <el-table :data="absentRecords" style="width: 100%" border stripe>
                            <el-table-column prop="attendanceDate" label="日期" width="180" />
                            <el-table-column prop="course.courseName" label="课程" width="210" />
                            <el-table-column prop="subjectName" label="科目" width="120" />
                            <el-table-column prop="course.teacher.nickName" label="任课教师" width="120" />
                            <el-table-column prop="remark" label="旷课原因">
                                <template #default="scope">
                                    <span v-if="scope.row.remark">{{ scope.row.remark }}</span>
                                    <span v-else>无原因说明</span>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                </el-tabs>
            </el-card>
        </template>
    </div>
</template>

<script setup name="StudentManagePersonOverview">
import { ref, getCurrentInstance, onMounted, onUnmounted, computed, nextTick, watch } from 'vue';
import { useRoute } from 'vue-router';
import useUserStore from '@/store/modules/user'
import { isHttp, isEmpty } from "@/utils/validate"
import defAva from '@/assets/images/profile.jpg'
import { allClass, allSubject } from "@/api/manage/course";
import { allStudent } from "@/api/system/user";
import { deptTreeSelect, allTeacher } from "@/api/system/user";
import { getDaysAttendanceRate, getDaysAttendanceRateByType, getDaysAttendanceStatistics, allAttendance } from "@/api/manage/attendance";
import { updateAttention_student } from "@/api/manage/attention_student";
import { listRequest } from "@/api/manage/request";
import { getDaysByOption } from "@/utils/lastDays";
import * as echarts from 'echarts';
import { Calendar, TrendCharts, Collection } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();
const { leave_status } = proxy.useDict('leave_status'); // 请假状态字典: 0已通过, 1待审批, 2审核未通过, 3已取消
const { attendance_status } = proxy.useDict('attendance_status'); // 考勤状态字典: 0到课, 1迟到, 2请假, 3旷课
const route = useRoute();
const userStore = useUserStore();

const isStudent = userStore.roles[0] === 'student' ? true : false; // 判断是否是学生角色

// 全局年级以及班级和学生的选择
const allClassData = ref([]);
const enabledDeptOptions = ref([]);
const allStudentData = ref([]);
const selectedGlobalDeptId = ref('');
const selectedGlobalClassId = ref('');
const selectedGlobalStudentId = ref('');
const showEmptyStudentTip = ref(false);

// 学生信息
const studentInfo = ref({});
const studentAttendanceRate = ref(0);

// 出勤统计
const attendanceStatsPeriod = ref('today');
const attendanceStats = ref({
    total: 0,
    normal: 0,
    late: 0,
    leave: 0,
    absent: 0,
    rate: 0
});

function getProcessedAvatar(avatar) {
    if (!isHttp(avatar)) {
        avatar = isEmpty(avatar) ? defAva : import.meta.env.VITE_APP_BASE_API + avatar;
    }
    return avatar;
}

// 学科列表
const subjectIdList = ref([]);

// 科目统计
const subjectStatsPeriod = ref('today');
const subjectStats = ref([]);

// 时间范围文本
const periodText = computed(() => {
    switch (attendanceStatsPeriod.value) {
        case 'today': return '日';
        case 'week': return '周';
        case 'month': return '月';
        case 'semester': return '学期';
        default: return '周';
    }
});

// 科目出勤率图表
const subjectChartPeriod = ref('today');
const subjectBarChart = ref(null);
let subjectChart = null;

// 请假记录
const leaveTabActive = ref('leaveList');
const leaveRecords = ref([]);
const lateRecords = ref([]);
const absentRecords = ref([]);

// 班级下拉框数据，获取所有班级
function getAllClass() {
    allClass().then(response => {
        allClassData.value = response.data;
        if (route.query.deptId == selectedGlobalDeptId.value && route.query.postId && route.query.studentId) {
            selectedGlobalClassId.value = route.query.postId;
            return;
        }
        // 如果有班级数据，默认选择第一个班级
        if (allClassData.value && allClassData.value.length > 0) {
            selectedGlobalClassId.value = allClassData.value[0].postId;
        }
    });
}

// 获取学科数据
function getAllSubject() {
    allSubject().then(response => {
        subjectIdList.value = response.data;
    });
}

/** 查询年级下拉树结构 */
function getDeptTree() {
    deptTreeSelect().then(response => {
        enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
        if (route.query.deptId && route.query.postId && route.query.studentId) {
            selectedGlobalDeptId.value = route.query.deptId;
            return;
        }
        // 默认选择第一个年级
        if (enabledDeptOptions.value && enabledDeptOptions.value.length > 0) {
            selectedGlobalDeptId.value = 233;
        }
    });
}

/** 过滤禁用的年级 */
function filterDisabledDept(deptList) {
    return deptList.filter(dept => {
        if (dept.disabled) {
            return false;
        }
        if (dept.id == 101) {
            return false;
        }
        if (dept.children && dept.children.length) {
            dept.children = filterDisabledDept(dept.children);
        }
        return true;
    });
}

// 获取学生数据
function getAllStudent() {
    allStudent({
        deptId: selectedGlobalDeptId.value,
        postId: selectedGlobalClassId.value
    }).then(response => {
        allStudentData.value = response.rows;
        // 按照id降序升序排序
        allStudentData.value.sort((a, b) => a.userId - b.userId);
        // 检查是否有学生数据
        if (route.query.deptId == selectedGlobalDeptId.value &&
            route.query.postId == selectedGlobalClassId.value &&
            route.query.studentId) {
            selectedGlobalStudentId.value = route.query.studentId;
            return;
        }
        if (!allStudentData.value || allStudentData.value.length === 0) {
            showEmptyStudentTip.value = true;
            selectedGlobalStudentId.value = '';
        } else {
            showEmptyStudentTip.value = false;
            // 默认选择第一个学生
            selectedGlobalStudentId.value = allStudentData.value[0].userId;
        }
    });
}

// 树形结构中查找指定ID的节点
function findDeptById(tree, id) {
    for (const node of tree) {
        if (node.id === id) {
            return node; // 找到目标节点，直接返回
        }
        if (node.children && node.children.length > 0) {
            const result = findDeptById(node.children, id); // 递归查找子节点
            if (result) {
                return result; // 如果在子节点中找到，返回结果
            }
        }
    }
    return null; // 如果未找到，返回 null
}

// 获取选中选中学生的名称
function getSelectedStudentName() {
    if (!selectedGlobalDeptId.value) {
        return '请先选择年级';
    }
    if (!selectedGlobalClassId.value) {
        return '请先选择班级';
    }
    if (!selectedGlobalStudentId.value) {
        return '请先选择学生';
    }

    // 获得当前所选年级，enabledDeptOptions是树形结构，不能直接循环找到
    const selectedDept = findDeptById(enabledDeptOptions.value, selectedGlobalDeptId.value);
    if (!selectedDept) {
        return '未知年级';
    }

    const selectedClass = allClassData.value.find(item => item.postId === selectedGlobalClassId.value);
    if (!selectedClass) {
        return '未知班级';
    }

    const selectedStudent = allStudentData.value.find(item => item.userId === selectedGlobalStudentId.value);
    if (!selectedStudent) {
        return '未知学生';
    }

    // 将班级名称和年级名称拼接
    if (selectedDept.label && selectedClass.postName) {
        return `${selectedDept.label}${selectedClass.postName}${selectedStudent.nickName}`;
    }

    return '未知学生';
}

// 获取选中班级的名称
function getSelectedClassName(data) {
    if (data) {
        const postId = data.postIds[0];
        // 从allClassData.value中找到对应的班级名称
        const postName = allClassData.value.find(item => item.postId === postId).postName;
        return `${data.dept.deptName}${postName}`;
    }
    if (!selectedGlobalDeptId.value) {
        return '未知年级';
    }
    if (!selectedGlobalClassId.value) {
        return '未知班级';
    }

    // 获得当前所选年级，enabledDeptOptions是树形结构，不能直接循环找到
    const selectedDept = findDeptById(enabledDeptOptions.value, selectedGlobalDeptId.value);
    if (!selectedDept) {
        return '未知年级';
    }

    const selectedClass = allClassData.value.find(item => item.postId === selectedGlobalClassId.value);
    if (!selectedClass) {
        return '未知班级';
    }

    // 将班级名称和年级名称拼接
    if (selectedDept.label && selectedClass.postName) {
        return `${selectedDept.label}${selectedClass.postName}`;
    }

    return '未知班级';
}

// 获取今天日期的函数，日期格式为YYYY-MM-DD
function getTodayDate() {
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
    const day = String(today.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

// 获取学科名称
function getSubjectName(subjectId) {
    const subject = subjectIdList.value.find(item => item.subjectId === subjectId);
    return subject ? subject.subjectName : '未知';
}

// 获取请假状态类型
function getLeaveStatusType(status) {
    switch (parseInt(status)) {
        case 0: // 已通过
            return 'success';
        case 1: // 待审批
            return 'warning';
        case 2: // 审核未通过
            return 'danger';
        case 3: // 已取消
            return 'info';
        default:
            return 'info';
    }
}

// 获取请假状态文本
function getLeaveStatusText(status) {
    const statusObj = leave_status.value.find(item => parseInt(item.value) === parseInt(status));
    return statusObj ? statusObj.label : '未知';
}

// 获取考勤状态文本
function getAttendanceStatusText(status) {
    const statusObj = attendance_status.value.find(item => parseInt(item.value) === parseInt(status));
    return statusObj ? statusObj.label : '未知';
}

// 查看请假详情
function viewLeaveDetail(row) {
    proxy.$modal.msgInfo(`查看请假详情：${row.reason}`);
}

// 获取学生信息
function getStudentInfo() {
    if (!selectedGlobalStudentId.value) return;

    // 获取选中的学生信息
    const selectedStudent = allStudentData.value.find(item => item.userId === selectedGlobalStudentId.value);
    if (selectedStudent) {
        studentInfo.value = selectedStudent;
    }
}

// 获取学生出勤率
function getStudentAttendanceRate() {
    if (!selectedGlobalStudentId.value) return;

    getDaysAttendanceStatistics({
        "days": getDaysByOption('semester'),
        "studentId": selectedGlobalStudentId.value
    }).then(res => {
        if (res.code === 200 && res.data) {
            // 总出勤率
            studentAttendanceRate.value = res.data.rate;
        } else {
            // 如果没有数据，设置为0
            studentAttendanceRate.value = 0;
        }
    }).catch(() => {
        studentAttendanceRate.value = 0;
    });
}

// 获取学生出勤统计
function getStudentAttendanceStats(period) {
    if (!selectedGlobalStudentId.value) return;

    getDaysAttendanceStatistics({
        "days": getDaysByOption(period),
        "studentId": selectedGlobalStudentId.value
    }).then(res => {
        if (res.code === 200 && res.data) {
            attendanceStats.value = {
                total: res.data.total || 0,
                normal: res.data.normal || 0,
                late: res.data.late || 0,
                leave: res.data.leave || 0,
                absent: res.data.absent || 0,
                rate: res.data.rate || 0
            };
        }
    }).catch(() => {
        // 重置统计数据
        attendanceStats.value = {
            total: 0,
            normal: 0,
            late: 0,
            leave: 0,
            absent: 0,
            rate: 0
        };
    });
}

// 获取学生科目出勤统计
function getStudentSubjectStats(period) {
    if (!selectedGlobalStudentId.value || !subjectIdList.value.length) return;

    const stats = [];
    const promises = subjectIdList.value.map(subject => {
        return getDaysAttendanceStatistics({
            "days": getDaysByOption(period),
            "studentId": selectedGlobalStudentId.value,
            "subjectId": subject.subjectId
        }).then(res => {
            if (res.code === 200 && res.data) {
                stats.push({
                    id: subject.subjectId,
                    name: subject.subjectName,
                    count: res.data.normal || 0
                });
            } else {
                stats.push({
                    id: subject.subjectId,
                    name: subject.subjectName,
                    count: 0
                });
            }
        }).catch(() => {
            stats.push({
                id: subject.subjectId,
                name: subject.subjectName,
                count: 0
            });
        });
    });

    Promise.all(promises).then(() => {
        subjectStats.value = stats.sort((a, b) => a.id - b.id);
    });
}

// 获取学生科目出勤率
function getStudentSubjectAttendanceRate(period) {
    const params = {
        "days": getDaysByOption(period),
        "studentId": selectedGlobalStudentId.value,
        "type": 'subject'
    };

    getDaysAttendanceRateByType(params).then(res => {
        if (res.code === 200) {
            initSubjectBarChart(res.data);
        } else {
            // 提示报错信息
            proxy.$modal.msgError('获取科目出勤率失败，请稍后重试！');
        }
    }).catch(() => {
        // 提示报错信息
        proxy.$modal.msgError('获取科目出勤率失败，请稍后重试！');
    });
}

// 初始化学科出勤率柱状图
function initSubjectBarChart(data) {
    if (!subjectBarChart.value) return;

    if (!data) return;

    // 使用API返回的数据
    const chartData = {
        subjects: data.nameList,
        rates: data.rateList
    };

    // 如果图表已经存在，销毁它
    if (subjectChart) {
        subjectChart.dispose();
    }

    // 创建新图表
    subjectChart = echarts.init(subjectBarChart.value);

    const option = {
        backgroundColor: '#fff',
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                return params[0].name + '<br/>' + params[0].marker + '出勤率: ' + params[0].value + '%';
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            top: '16%', // 增加顶部边距，避免数据标签被遮挡
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: chartData.subjects,
            axisLine: {
                lineStyle: {
                    color: '#ddd'
                }
            },
            axisLabel: {
                color: '#666'
            }
        },
        yAxis: {
            type: 'value',
            min: 0,
            max: 100,
            axisLine: {
                show: false
            },
            axisLabel: {
                color: '#666',
                formatter: '{value}%'
            },
            splitLine: {
                lineStyle: {
                    color: '#eee'
                }
            }
        },
        series: [
            {
                name: '出勤率',
                type: 'bar',
                barWidth: '40%',
                itemStyle: {
                    color: '#4080ff'
                },
                data: chartData.rates
            }
        ]
    };

    subjectChart.setOption(option);

    // 添加点击事件
    subjectChart.on('click', function (params) {
        // 显示当前学科的出勤率
        proxy.$message.info(`${params.name}出勤率: ${params.value}%`);
    });
}

// 获取学生请假记录
function getStudentLeaveRecords() {
    if (!selectedGlobalStudentId.value) return;

    // 获取请假记录
    listRequest({
        studentId: selectedGlobalStudentId.value
    }).then(response => {
        if (response.code === 200 && response.rows) {
            leaveRecords.value = response.rows;
            // 按照leaveId从大到小排序，并且只取排序后的前十条展示
            leaveRecords.value.sort((a, b) => b.leaveId - a.leaveId);
            leaveRecords.value = leaveRecords.value.slice(0, 10);
        } else {
            leaveRecords.value = [];
        }
    }).catch(() => {
        leaveRecords.value = [];
    });
}

// 获取迟到和旷课记录
function getAttendanceRecords() {
    if (!selectedGlobalStudentId.value) return;

    // 获取所有考勤记录
    allAttendance({
        studentId: selectedGlobalStudentId.value,
        attendanceDate: getTodayDate() // 获取今天的日期
    }).then(response => {
        if (response.code === 200 && response.data) {
            // 筛选迟到记录 (status=1)
            lateRecords.value = response.data.filter(record => parseInt(record.status) === 1);

            // 筛选旷课记录 (status=3)
            absentRecords.value = response.data.filter(record => parseInt(record.status) === 3);
        } else {
            lateRecords.value = [];
            absentRecords.value = [];
        }
    }).catch(() => {
        lateRecords.value = [];
        absentRecords.value = [];
    });
}

// 设置为重点关注学生
function handleAddAttention() {
    if (!selectedGlobalStudentId.value) {
        proxy.$modal.msgError('请先选择学生');
        return;
    }

    proxy.$modal.confirm('确认将该学生设置为重点关注学生吗？').then(() => {
        updateAttention_student({
            studentId: selectedGlobalStudentId.value,
            reason: '出勤率低',
            status: 0,
            startDate: getTodayDate(),
            endDate: new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]
        }).then(response => {
            if (response.code == 200) {
                // 设置成功
                proxy.$modal.msgSuccess('设置成功');
            } else {
                // 设置失败
                proxy.$modal.msgError('设置失败，请稍后重试！');

            }
        }).catch(() => {
            // 处理错误
            proxy.$modal.msgError('设置失败，请稍后重试！');
        });
    }).catch(() => {
        // 用户取消操作
        proxy.$modal.msgInfo('操作已取消');
    });
}


// 监听全局年级变化
watch(selectedGlobalDeptId, (newVal) => {
    // 当年级变化时，重置班级选择
    if (allClassData.value && allClassData.value.length > 0) {
        if (route.query.deptId == newVal && route.query.postId && route.query.studentId) {
            selectedGlobalClassId.value = route.query.postId;
        } else {
            selectedGlobalClassId.value = allClassData.value[0].postId;
        }
    } else {
        selectedGlobalClassId.value = '';
    }
    selectedGlobalStudentId.value = '';
    if (selectedGlobalClassId.value) {
        getAllStudent();
    }
});

// 监听全局班级变化
watch(selectedGlobalClassId, (newVal) => {
    if (!newVal) {
        selectedGlobalStudentId.value = '';
        return;
    }
    // 更新学生数据
    selectedGlobalStudentId.value = '';
    if (selectedGlobalDeptId.value) {
        getAllStudent();
    }
});

// 监听全局学生变化
watch(selectedGlobalStudentId, (newVal) => {
    if (!newVal) {
        showEmptyStudentTip.value = true;
        return
    }
    showEmptyStudentTip.value = false;

    // 获取学生信息和统计数据
    getStudentInfo();
    getStudentAttendanceRate();
    getStudentAttendanceStats(attendanceStatsPeriod.value);
    getStudentSubjectStats(subjectStatsPeriod.value);
    getStudentSubjectAttendanceRate(subjectChartPeriod.value);
    getStudentLeaveRecords();
    getAttendanceRecords();
});

// 监听统计周期变化
watch(attendanceStatsPeriod, (newVal) => {
    getStudentAttendanceStats(newVal);
});

watch(subjectStatsPeriod, (newVal) => {
    getStudentSubjectStats(newVal);
});

watch(subjectChartPeriod, (newVal) => {
    getStudentSubjectAttendanceRate(newVal);
});

onMounted(() => {
    // 将route.query的值转换为数字类型
    if (route.query.deptId && route.query.postId && route.query.studentId) {
        route.query.deptId = parseInt(route.query.deptId);
        route.query.postId = parseInt(route.query.postId);
        route.query.studentId = parseInt(route.query.studentId);
    }
    // 获取基础数据
    getDeptTree();
    getAllClass();
    getAllSubject();
    if (isStudent) {
        getAllStudent();
    }

    // 初始化图表
    nextTick(() => {
        getStudentSubjectAttendanceRate("today");

        // 监听窗口大小变化，重绘图表
        window.addEventListener('resize', () => {
            // 重新绘制图表前检查图表实例是否存在
            if (subjectChart) {
                subjectChart.resize();
            }
        });
    });
});

// 组件卸载时清理
onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', () => { });

    // 销毁图表实例前检查是否存在
    if (subjectChart) {
        subjectChart.dispose();
    }
});
</script>

<style scoped>
.timetable-container {
    padding: 20px;
}

/* 班级选择样式 */
.class-select {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    background-color: #fff;
}

.class-select:hover {
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 鼠标悬停时显示阴影 */
}

.select-info {
    display: flex;
    align-items: center;
    margin-left: 10px;
    font-weight: bold;
}

.select-filter {
    display: flex;
    gap: 10px;
    align-items: center;
}

.filter-item {
    height: 32px;
    margin-left: 10px;
}

/* 学生信息卡片样式 */
.info-card {
    margin-bottom: 20px;
    border-radius: 8px;
    position: relative;
    /* 确保卡片有相对定位 */
}

.focus-button {
    position: absolute;
    top: 10px;
    right: 10px;
    z-index: 1;
}

.student-info {
    display: flex;
    align-items: center;
    padding: 10px;
}

.student-avatar {
    margin-right: 20px;
}

.user-avatar {
    cursor: pointer;
    width: 80px;
    height: 80px;
    /* 增加圆角 */
    border-radius: 30%;
}

.student-details {
    flex: 1;
}

.info-row {
    display: flex;
    margin-bottom: 10px;
}

.info-item {
    display: flex;
    align-items: center;
    margin-right: 30px;
}

.label {
    font-weight: bold;
    margin-right: 5px;
    color: #606266;
}

.value {
    color: #303133;
}

.attendance-rate {
    color: #67c23a;
    font-weight: bold;
}

/* 图表卡片样式 */
.chart-card {
    border-radius: 8px;
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.card-header .title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    display: flex;
    align-items: center;
}

.card-header .title .el-icon {
    margin-right: 5px;
}

/* 出勤统计样式 - 调整后的横排布局 */
.attendance-stats-container {
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
    padding: 10px 0;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
    background-color: #fafafa;
    border-radius: 4px;
}

.attendance-stats-item {
    text-align: center;
    padding: 10px 15px;
    flex: 1;
    min-width: 120px;
}

.stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #409EFF;
    margin-bottom: 5px;
}

.stat-label {
    font-size: 14px;
    color: #606266;
}

/* 科目统计样式 - 调整后的网格布局 */
.subject-stats-container {
    padding: 10px 0;
}

.subject-stats-row {
    display: flex;
    justify-content: flex-start;
    margin-bottom: 10px;
}

/* 科目统计样式 - 优化后的网格布局 */
.subject-stats-grid {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 10px;
    padding: 15px;
    background-color: #fafafa;
    border-radius: 4px;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
}

.subject-stats-item {
    text-align: center;
    padding: 10px 15px;
    min-width: 120px;
    flex: 0 0 25%;
    /* 每行4个项目 */
}

/* 图表容器样式 */
.chart-container {
    height: 300px;
    width: 100%;
}

.radio-group-inline {
    display: flex;
    flex-wrap: nowrap;
}

/* 请假原因一列的样式 */
.ellipsis {
    display: inline-block;
    max-width: 380px;
    /* 根据需要调整宽度 */
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    vertical-align: middle;
}

/* 响应式调整 */
@media (max-width: 768px) {
    .select-filter {
        flex-direction: column;
        align-items: flex-start;
    }

    .info-row {
        flex-direction: column;
    }

    .info-item {
        margin-bottom: 5px;
    }

    .attendance-stats-container {
        flex-direction: column;
    }

    .subject-stats-row {
        flex-wrap: wrap;
    }

    .subject-stats-item {
        flex: 0 0 50%;
        /* 在小屏幕上每行2个项目 */
    }
}
</style>